<?php

	/**
	 * @package		CoreProject
	 * @subpackage	Mime
	 *
	 * cpr_Mime_Attachment
	 * cpr_Mime_Attachments
	 * 
	 */

	class cpr_Mime_Attachment
	{
		/**
		 * @var	string
		 */
		private $_filename = '';

		/**
		 * @var	cpr_Mime_MimePart
		 */
		private $_mime;

		/**
		 * @var	cpr_Mime_GlobalCharset
		 */
		private $_global_charset;

		/**
		 * @param	cpr_Mime_GlobalCharset	$_gc
		 * @param	cpr_Mime_MimePart		$_mime
		 * @return	cpr_Mime_Attachment
		 */
		public function cpr_Mime_Attachment(&$_gc, &$_mime)
		{
			$this->_global_charset =& $_gc;
			$this->_mime =& $_mime;
			$this->_fillFileNameFromMime();
		}

		/**
		 * @return	string
		 */
		public function FileName()
		{
			return $this->_filename;
		}

		/**
		 * @return	string
		 */
		public function BinaryBody()
		{
			return $this->_mime->GetBinaryBody();
		}

		private function _fillFileNameFromMime()
		{
			$result = '';
			$_headers = null;
			if ($this->_mime)
			{
				$_headers =& $this->_mime->GetHeaders();
			}

			if (!$_headers)
			{
				return false;
			}
			
			$filename = $_headers->GetFileName();
			if ($filename === '')
			{
				$contentName = $_headers->GetContentTypeName();
				if ($contentName)
				{
					$result = $contentName;
				}
				else
				{
					$contentTypeL = strtolower($_headers->GetContentType());
					$result = (false !== strpos($contentTypeL, CPR_MIME_IMAGE_L) || false !== strpos($contentTypeL, CPR_MIME_MESSAGE_L))
						? str_replace(array('/', '\\'), '.', $contentTypeL) : CPR_MIME_NO_NAME_ATTACH;
				}
			}
			else
			{
				$result = $filename;
			}

			$this->_filename = $result;
		}
	}

	class cpr_Mime_Attachments extends cpr_Core_Collection
	{
		/**
		 * @var	cpr_Mime_GlobalCharset
		 */
		private $_global_charset;

		/**
		 * @param	cpr_Mime_GlobalCharset	$_gc
		 * @param	cpr_Mime_MimePart		$_mime
		 * @return	cpr_Mime_Attachments
		 */
		public function cpr_Mime_Attachments(&$_gc, &$_mime)
		{
			$this->_global_charset =& $_gc;
			$this->_searchAttachments($_mime);
		}

		/**
		 * @param	cpr_Mime_MimePart	$mimePart
		 */
		private function _searchAttachments(&$mimePart)
		{
			if (!$mimePart)
			{
				return false;
			}
			$subParts =& $mimePart->GetSubParts();
			if (null === $subParts)
			{
				$_headers =& $mimePart->GetHeaders();
				if ($_headers && $_headers->IsAttachmentHeader())
				{
					$this->Add(new cpr_Mime_Attachment($this->_global_charset, $mimePart));
				}
			}
			else
			{
				for ($i = 0, $c = $subParts->Count(); $i < $c; $i++)
				{
					$subPart =& $subParts->Get($i);
					$this->_searchAttachments($subPart);
					unset($subPart);
				}
			}
			return true;
		}
	}
